package com.nahan.secondapplication.ImitateDouYin;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.widget.NestedScrollView;

import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.nahan.secondapplication.App;
import com.nahan.secondapplication.R;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;

/**
 * 评论框dialog fragment
 */
public class CommentBottomSheetDialogFragment extends BottomSheetDialogFragment implements OnRefreshLoadMoreListener {

    private CommentListEntity bean;
    private CommentExpandableListView expandableListView;
    private CommentExpandAdapter adapter;
    private BottomSheetDialog dialog;
    private ImageView close;
    private Context context;

    private SmartRefreshLayout smart_layout;

    private LinearLayout aa;
    private RelativeLayout bb;
    private TextView cc;
    private TextView tv;

    private LinearLayout ll_nothing;
    private NestedScrollView sv_ding;

    private int page = 1;
    private int totalPage;//最大页数

    private float slideOffset = 0;

    public CommentBottomSheetDialogFragment(Context context, CommentListEntity entity) {
        this.bean = entity;
        this.context = context;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        //给dialog设置主题为透明背景 不然会有默认的白色背景
        setStyle(BottomSheetDialogFragment.STYLE_NORMAL, R.style.CustomBottomSheetDialogTheme);

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // 在这里将view的高度设置为精确高度，即可屏蔽向上滑动不占全屏的手势。
        //如果不设置高度的话 会默认向上滑动时dialog覆盖全屏
        final View view = inflater.inflate(R.layout.dialog_comment, container, false);

//        view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
//                MyUtils.getScreenHeight(context)/3));
        expandableListView = (CommentExpandableListView) view.findViewById(R.id.detail_page_lv_comment);
        close = (ImageView) view.findViewById(R.id.close);
        smart_layout = (SmartRefreshLayout) view.findViewById(R.id.smart_layout);
        ll_nothing= (LinearLayout) view.findViewById(R.id.ll_nothing);
        aa = (LinearLayout) view.findViewById(R.id.aa);
        bb = (RelativeLayout) view.findViewById(R.id.bb);
        cc = (TextView) view.findViewById(R.id.cc);
        tv = (TextView) view.findViewById(R.id.tv);
        sv_ding = (NestedScrollView) view.findViewById(R.id.sv_ding);


        if (bean==null||bean.getRows().size()<1)
        {
            ll_nothing.setVisibility(View.VISIBLE);
        }


        smart_layout.setEnableRefresh(false);
        smart_layout.setEnableLoadMore(false);
        smart_layout.setOnRefreshLoadMoreListener(this);
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });




        return view;
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
//        final RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.detail_page_lv_comment);
//        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
//        recyclerView.setAdapter(new ItemAdapter(100));

        view.findViewById(R.id.tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                InputDialog inputDialog = new InputDialog(getActivity());
//                Window window = inputDialog.getWindow();
//                WindowManager.LayoutParams params = window.getAttributes();
//                window.setSoftInputMode(params.SOFT_INPUT_STATE_VISIBLE);
//                inputDialog.show();
                showCommentDialog();
            }
        });




        initView();
    }


    private void initView() {
        expandableListView.setGroupIndicator(null);

        //默认展开所有回复
        adapter = new CommentExpandAdapter(App.getInstance(), bean.getRows());
        expandableListView.setAdapter(adapter);

        for (int i = 0; i < bean.getRows().size(); i++) {
            expandableListView.expandGroup(i);
        }

        expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView expandableListView, View view, int groupPosition, long l) {
                boolean isExpanded = expandableListView.isGroupExpanded(groupPosition);
                Log.e("当前的评论id>>>", bean.getRows().get(groupPosition).getUserId() + "");
//                if(isExpanded){
//                    expandableListView.collapseGroup(groupPosition);
//                }else {
//                    expandableListView.expandGroup(groupPosition, true);
//                }
                showReplyDialog(groupPosition);
                return true;
            }
        });

        expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView expandableListView, View view, int groupPosition, int childPosition, long l) {
                showSecondLevelReplyDialog(groupPosition, childPosition);
                return false;
            }
        });

        expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
            @Override
            public void onGroupExpand(int groupPosition) {
//                ToastUtil.toastShortMessage("展开第"+groupPosition+"个分组");

            }
        });
    }

    /**
     * 如果想要点击外部消失的话 重写此方法
     *
     * @param savedInstanceState
     * @return
     */
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        BottomSheetDialog dialog = (BottomSheetDialog)super.onCreateDialog(savedInstanceState);

        //设置点击外部可消失
        dialog.setCanceledOnTouchOutside(true);

        //设置使软键盘弹出的时候dialog不会被顶起
        Window win = dialog.getWindow();
        WindowManager.LayoutParams params = win.getAttributes();
        win.setSoftInputMode(params.SOFT_INPUT_ADJUST_NOTHING);

        //这里设置dialog的进出动画
        win.setWindowAnimations(R.style.DialogBottomAnim);


        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                hideSoftInput(getActivity());
            }
        });


        return dialog;


    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onStart() {
        super.onStart();
        BottomSheetDialog dialog = (BottomSheetDialog)getDialog();




        final View view = getView();
        BottomSheetBehavior mDialogBehavior = BottomSheetBehavior.from((View) view.getParent());
        mDialogBehavior.setPeekHeight(getWindowHeight());

        //dialog滑动监听
        mDialogBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
                    if (newState == BottomSheetBehavior.STATE_HIDDEN) {
                        mDialogBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                    } else if (newState == BottomSheetBehavior.STATE_SETTLING) {
                        if (slideOffset <= -0.28) {
                            //当向下滑动时 值为负数
                            dismiss();
                        }
                    }

            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffse) {
               slideOffset = slideOffse;//记录滑动值
            }
        });


        sv_ding.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (sv_ding.getScrollY() == 0) {
                    //顶部
                    mDialogBehavior.setHideable(true);
                }else
                {
                    mDialogBehavior.setHideable(false);
                }

                View contentView = sv_ding.getChildAt(0);
                if (contentView != null && contentView.getMeasuredHeight() == (sv_ding.getScrollY() + sv_ding.getHeight())) {
                    //底部
                }
            }
        });
    }

    private int getWindowHeight() {
        Resources res = getResources();
        DisplayMetrics displayMetrics = res.getDisplayMetrics();
        return displayMetrics.heightPixels;
    }

    /**
     * by moos on 2018/04/20
     * func:弹出评论框
     */
    private void showCommentDialog() {
        dialog = new BottomSheetDialog(context, R.style.CommentBottomSheetStyle);
        View commentView = LayoutInflater.from(context).inflate(R.layout.comment_dialog_layout, null);
        final EditText commentText = (EditText) commentView.findViewById(R.id.dialog_comment_et);
        final Button bt_comment = (Button) commentView.findViewById(R.id.dialog_comment_bt);

        dialog.setContentView(commentView);
        showSoftInputFromWindow((Activity) context, commentText);
        /**
         * 解决bsd显示不全的情况
         */
        View parent = (View) commentView.getParent();
        BottomSheetBehavior behavior = BottomSheetBehavior.from(parent);
        commentView.measure(0, 0);
        behavior.setPeekHeight(commentView.getMeasuredHeight());

        bt_comment.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                String commentContent = commentText.getText().toString().trim();
                if (!TextUtils.isEmpty(commentContent)) {
                    savecomment(commentContent);
                    //commentOnWork(commentContent);
                    dialog.dismiss();


                } else {
                    Toast.makeText(context, "评论内容不能为空", Toast.LENGTH_SHORT).show();
                }
            }
        });
        commentText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (!TextUtils.isEmpty(charSequence) && charSequence.length() > 2) {
                    bt_comment.setBackgroundColor(getResources().getColor(R.color.color_red));
                } else {
                    bt_comment.setBackgroundColor(Color.parseColor("#D8D8D8"));
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        dialog.show();
    }


    /**
     * by moos on 2018/04/20
     * func:弹出回复框
     */
    private void showReplyDialog(final int position) {
        dialog = new BottomSheetDialog(context, R.style.CommentBottomSheetStyle);
        View commentView = LayoutInflater.from(context).inflate(R.layout.comment_dialog_layout, null);
        final EditText commentText = (EditText) commentView.findViewById(R.id.dialog_comment_et);
        final Button bt_comment = (Button) commentView.findViewById(R.id.dialog_comment_bt);

        commentText.setHint("回复 " + bean.getRows().get(position).getUserName() + " 的评论:");
        dialog.setContentView(commentView);
        showSoftInputFromWindow((Activity) context, commentText);
        bt_comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String replyContent = commentText.getText().toString().trim();
                if (!TextUtils.isEmpty(replyContent)) {

                    dialog.dismiss();
                    replycommrt(bean.getRows().get(position).getUserId(), position, replyContent, bean.getRows().get(position).getUserName(), bean.getRows().get(position).getCommentId());


                } else {
                    Toast.makeText(context, "回复内容不能为空", Toast.LENGTH_SHORT).show();
                }
            }
        });
        commentText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (!TextUtils.isEmpty(charSequence) && charSequence.length() > 2) {
                    bt_comment.setBackgroundColor(getResources().getColor(R.color.color_red));
                } else {
                    bt_comment.setBackgroundColor(Color.parseColor("#D8D8D8"));
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        dialog.show();

    }

    /**
     * 弹出二级回复框
     *
     * @param groupPosition
     * @param childPosition
     */
    private void showSecondLevelReplyDialog(int groupPosition, int childPosition) {

        dialog = new BottomSheetDialog(context, R.style.CommentBottomSheetStyle);
        View commentView = LayoutInflater.from(context).inflate(R.layout.comment_dialog_layout, null);
        final EditText commentText = (EditText) commentView.findViewById(R.id.dialog_comment_et);
        final Button bt_comment = (Button) commentView.findViewById(R.id.dialog_comment_bt);

        commentText.setHint("回复 " + bean.getRows().get(groupPosition).getReplys().get(childPosition).getReplyUserName() + " 的评论:");
        dialog.setContentView(commentView);
        showSoftInputFromWindow((Activity) context, commentText);
        bt_comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String replyContent = commentText.getText().toString().trim();
                if (!TextUtils.isEmpty(replyContent)) {

                    dialog.dismiss();
                    replycommrt(-1,
                            groupPosition,
                            replyContent,
                            bean.getRows().get(groupPosition).getReplys().get(childPosition).getReplyUserName(),
                            bean.getRows().get(groupPosition).getCommentId());


                } else {
                    Toast.makeText(context, "回复内容不能为空", Toast.LENGTH_SHORT).show();
                }
            }
        });
        commentText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (!TextUtils.isEmpty(charSequence) && charSequence.length() > 2) {
                    bt_comment.setBackgroundColor(Color.parseColor("#FFB568"));
                } else {
                    bt_comment.setBackgroundColor(Color.parseColor("#D8D8D8"));
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        dialog.show();
    }

    /**
     * EditText获取焦点并显示软键盘
     */
    public static void showSoftInputFromWindow(Activity activity, EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        //显示软键盘
        activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        //如果上面的代码没有弹出软键盘 可以使用下面另一种方式
        //InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        // imm.showSoftInput(editText, 0);
    }


    /**
     * 评论上传
     *
     * @param commentContent
     */
    private void savecomment(String commentContent) {

                        ll_nothing.setVisibility(View.GONE);
                        CommentListEntity.RowsBean detailBean = new CommentListEntity.RowsBean(
                                1,
                                1,
                                1,
                                "不知道",
                                "touxiang",
                                commentContent,
                                "头像",
                                "刚刚",
                                0,
                                0,
                                0,
                                null
                        );
                        adapter.addTheCommentData(detailBean);
                        Toast.makeText(context, "评论成功", Toast.LENGTH_SHORT).show();
    }

    /**
     * 回复上传
     *
     * @param position
     * @param name
     * @param replyContent
     * @param commentId
     */
    private void replycommrt(int userId, int position, String replyContent, String name, int commentId) {
                        String reply;
                        String replyUserId;
                        reply = replyContent;
                        CommentListEntity.RowsBean.ReplysBean detailBean = new CommentListEntity.RowsBean.ReplysBean(
                                "测试",
                                "哈哈",
                                reply,
                                "刚刚",
                                "头像",
                                name);
                        adapter.addTheReplyData(detailBean, position);
                        expandableListView.expandGroup(position);
                        Toast.makeText(context, "回复成功", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        page++;
        CommentList();

    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {

    }


    /**
     * 加载评论回复数据
     */
    private void CommentList() {

//                adapter.addData(entity.getData().getRows(), expandableListView);
//
//                closerefreshlayout();
    }

    /**
     * 有数据时
     */
    private void closerefreshlayout() {
        smart_layout.finishLoadMore();//结束加载
        smart_layout.finishRefresh();//结束刷新
    }

    /**
     * 没有数据时
     */
    private void closefaillayout() {
        smart_layout.finishLoadMore(false);//结束加载
        smart_layout.finishRefresh(false);//结束刷新
    }

    /**
     * activity隐藏软键盘
     *
     * @param activity
     */
    public static void hideSoftInput(Activity activity) {
        View view = activity.getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager inputmanger = (InputMethodManager) activity.getSystemService(activity.INPUT_METHOD_SERVICE);
            inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }


}
